package leetcode_题库;

import java.util.Stack;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Ding
 * @create 2022/9/7 19:52
 */
public class _1592_重新排列单词间的空格 {
    public static void main(String[] args) {
//        String str = "  this   is  a sentence ";
//        String str = " practice   makes   perfect";
        String str = "  hello";
        System.err.println(reorderSpaces2(str));
    }

    private static String reorderSpaces2(String text) {
        int wordCount = 0;
        int spaceCount = 0;

        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == ' ') {
                spaceCount++;
                if (!stack.isEmpty() && stack.peek() != ' ') {
                    wordCount++;
                }
            }
            stack.push(text.charAt(i));
        }

        if (spaceCount == 0) {
            return text;
        }
        wordCount += stack.peek() == ' ' ? 0 : 1;

        StringBuilder sb = new StringBuilder();
        int insertCount = wordCount - 1;
        while (!stack.isEmpty()) {
            char c = stack.pop();
            if (c == ' ') {
                if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ' && insertCount-- > 0) {
                    for (int i = 0; i < spaceCount / (wordCount - 1); i++) {
                        sb.append(' ');
                    }
                }
            } else {
                sb.append(c);
            }
        }
        sb.reverse();
        int lastInsert = wordCount > 1 ? spaceCount % (wordCount - 1) : spaceCount;
        for (int i = 0; i < lastInsert; i++) {
            sb.append(' ');
        }
        return sb.toString();
    }

    public static String reorderSpaces(String text) {
        int wordCount = 0;
        int spaceCount = 0;
        char[] chars = text.toCharArray();

        boolean findWord = false;
        for (char c : chars) {
            if (c == ' ') {
                spaceCount++;
                findWord = false;
            } else {
                if (!findWord) {
                    wordCount++;
                    findWord = true;
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        findWord = false;
        int findWordIndex = 0;
        for (char c : chars) {
            if (c != ' ') {
                sb.append(c);
                findWord = true;
            } else if (findWord && findWordIndex < wordCount) {
                for (int i = 0; i < spaceCount / (wordCount - 1); i++) {
                    sb.append(' ');
                }
                findWord = false;
                findWordIndex++;
            }
        }

        for (int i = 0; i < spaceCount % (wordCount - 1); i++) {
            sb.append(' ');
        }

        System.err.println(spaceCount + "__" + wordCount);
        return sb.toString();
    }
}
